<template>
  <div class="app-container">
    <!-- 仓库、库区和库位信息 -->
    <el-card shadow="never" class="mb20">
      <div slot="header">
        <span>库存管理 - {{ warehouseInfo.warehouseName }} / {{ areaInfo.areaName }} / {{ locationInfo.locationCode }}</span>
        <el-button
          style="float: right; padding: 3px 0"
          type="text"
          icon="el-icon-back"
          @click="handleBack"
        >返回库位列表</el-button>
      </div>
      <el-descriptions :column="3" border>
        <el-descriptions-item label="库位类型">
          <dict-tag :options="locationTypeOptions" :value="locationInfo.locationType"/>
        </el-descriptions-item>
        <el-descriptions-item label="库位状态">
          <dict-tag :options="statusOptions" :value="locationInfo.status"/>
        </el-descriptions-item>
        <el-descriptions-item label="库存总数">{{ inventoryCount }}</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 查询条件 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true">
      <el-form-item label="物料编码" prop="materialCode">
        <el-input
          v-model="queryParams.materialCode"
          placeholder="请输入物料编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物料名称" prop="materialName">
        <el-input
          v-model="queryParams.materialName"
          placeholder="请输入物料名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="批次号" prop="batchNo">
        <el-input
          v-model="queryParams.batchNo"
          placeholder="请输入批次号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="handleAdd"
          v-hasPermi="['wms:inventory:add']"
        >入库</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-minus"
          @click="handleOut"
          v-hasPermi="['wms:inventory:out']"
        >出库</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-refresh"
          @click="handleTransfer"
          v-hasPermi="['wms:inventory:transfer']"
        >移库</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-document"
          @click="handleCheck"
          v-hasPermi="['wms:inventory:check']"
        >盘点</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          icon="el-icon-download"
          @click="handleExport"
          v-hasPermi="['wms:inventory:export']"
        >导出</el-button>
      </el-col>
    </el-row>

    <!-- 表格数据 -->
    <el-table
      v-loading="loading"
      :data="inventoryList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="物料编码" align="center" prop="materialCode" />
      <el-table-column label="物料名称" align="center" prop="materialName" />
      <el-table-column label="批次号" align="center" prop="batchNo" />
      <el-table-column label="库存数量" align="center" prop="quantity" />
      <el-table-column label="单位" align="center" prop="unit" />
      <el-table-column label="生产日期" align="center" prop="productionDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.productionDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="过期日期" align="center" prop="expiryDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.expiryDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="库存状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="inventoryStatusOptions" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['wms:inventory:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
            v-hasPermi="['wms:inventory:query']"
          >详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 入库对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="物料编码" prop="materialCode">
          <el-input v-model="form.materialCode" placeholder="请输入物料编码" />
        </el-form-item>
        <el-form-item label="物料名称" prop="materialName">
          <el-input v-model="form.materialName" placeholder="请输入物料名称" />
        </el-form-item>
        <el-form-item label="批次号" prop="batchNo">
          <el-input v-model="form.batchNo" placeholder="请输入批次号" />
        </el-form-item>
        <el-form-item label="库存数量" prop="quantity">
          <el-input-number v-model="form.quantity" :min="1" :step="1" />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="form.unit" placeholder="请输入单位" />
        </el-form-item>
        <el-form-item label="生产日期" prop="productionDate">
          <el-date-picker
            v-model="form.productionDate"
            type="date"
            placeholder="选择生产日期"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        <el-form-item label="过期日期" prop="expiryDate">
          <el-date-picker
            v-model="form.expiryDate"
            type="date"
            placeholder="选择过期日期"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listInventory, getInventory, addInventory, updateInventory, deleteInventory, countInventory } from "@/api/wms";
import { getWarehouse } from "@/api/wms";
import { getArea } from "@/api/wms";
import { getLocation } from "@/api/wms";
import { getDicts } from "@/api/system/dict/data";

export default {
  name: "Inventory",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 库存表格数据
      inventoryList: [],
      // 仓库信息
      warehouseInfo: {},
      // 库区信息
      areaInfo: {},
      // 库位信息
      locationInfo: {},
      // 库存总数
      inventoryCount: 0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 状态数据字典
      statusOptions: [],
      // 库位类型数据字典
      locationTypeOptions: [],
      // 库存状态数据字典
      inventoryStatusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        warehouseId: undefined,
        areaId: undefined,
        locationId: undefined,
        materialCode: undefined,
        materialName: undefined,
        batchNo: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        materialCode: [
          { required: true, message: "物料编码不能为空", trigger: "blur" }
        ],
        materialName: [
          { required: true, message: "物料名称不能为空", trigger: "blur" }
        ],
        batchNo: [
          { required: true, message: "批次号不能为空", trigger: "blur" }
        ],
        quantity: [
          { required: true, message: "库存数量不能为空", trigger: "blur" }
        ],
        unit: [
          { required: true, message: "单位不能为空", trigger: "blur" }
        ],
        productionDate: [
          { required: true, message: "生产日期不能为空", trigger: "change" }
        ],
        expiryDate: [
          { required: true, message: "过期日期不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    const warehouseId = this.$route.query.warehouseId;
    const areaId = this.$route.query.areaId;
    const locationId = this.$route.query.locationId;
    if (warehouseId && areaId && locationId) {
      this.queryParams.warehouseId = warehouseId;
      this.queryParams.areaId = areaId;
      this.queryParams.locationId = locationId;
      this.getWarehouseInfo(warehouseId);
      this.getAreaInfo(areaId);
      this.getLocationInfo(locationId);
      this.getInventoryCount();
      this.getList();
      this.getDicts();
    } else {
      this.$modal.msgError("缺少仓库ID、库区ID或库位ID参数");
      this.handleBack();
    }
  },
  methods: {
    /** 查询库存列表 */
    getList() {
      this.loading = true;
      listInventory(this.queryParams).then(response => {
        this.inventoryList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 获取仓库信息
    getWarehouseInfo(warehouseId) {
      getWarehouse(warehouseId).then(response => {
        this.warehouseInfo = response.data;
      });
    },
    // 获取库区信息
    getAreaInfo(areaId) {
      getArea(areaId).then(response => {
        this.areaInfo = response.data;
      });
    },
    // 获取库位信息
    getLocationInfo(locationId) {
      getLocation(locationId).then(response => {
        this.locationInfo = response.data;
      });
    },
    // 获取库存总数
    getInventoryCount() {
      countInventory({ locationId: this.queryParams.locationId }).then(response => {
        this.inventoryCount = response.data;
      });
    },
    // 获取数据字典
    getDicts() {
      getDicts("sys_normal_disable").then(response => {
        this.statusOptions = response.data;
      });
      getDicts("wms_location_type").then(response => {
        this.locationTypeOptions = response.data;
      });
      getDicts("wms_inventory_status").then(response => {
        this.inventoryStatusOptions = response.data;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        inventoryId: undefined,
        warehouseId: this.queryParams.warehouseId,
        areaId: this.queryParams.areaId,
        locationId: this.queryParams.locationId,
        materialCode: undefined,
        materialName: undefined,
        batchNo: undefined,
        quantity: 1,
        unit: undefined,
        productionDate: undefined,
        expiryDate: undefined,
        status: "0",
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.inventoryId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 入库按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "入库操作";
    },
    /** 出库按钮操作 */
    handleOut() {
      if (this.single) {
        this.$modal.msgError("请选择一条记录进行操作");
        return;
      }
      this.$prompt('请输入出库数量', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^[1-9]\d*$/,
        inputErrorMessage: '出库数量必须为正整数'
      }).then(({ value }) => {
        // 调用出库API
        this.$modal.msgSuccess(`已出库 ${value} 件`);
      }).catch(() => {});
    },
    /** 移库按钮操作 */
    handleTransfer() {
      if (this.single) {
        this.$modal.msgError("请选择一条记录进行操作");
        return;
      }
      this.$prompt('请输入目标库位编码', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /\S+/,
        inputErrorMessage: '库位编码不能为空'
      }).then(({ value }) => {
        // 调用移库API
        this.$modal.msgSuccess(`已移动到库位 ${value}`);
      }).catch(() => {});
    },
    /** 盘点按钮操作 */
    handleCheck() {
      if (this.single) {
        this.$modal.msgError("请选择一条记录进行操作");
        return;
      }
      this.$prompt('请输入实际库存数量', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^[0-9]\d*$/,
        inputErrorMessage: '库存数量必须为非负整数'
      }).then(({ value }) => {
        // 调用盘点API
        this.$modal.msgSuccess(`盘点完成，实际库存 ${value} 件`);
      }).catch(() => {});
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const inventoryId = row.inventoryId || this.ids;
      getInventory(inventoryId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改库存";
      });
    },
    /** 详情按钮操作 */
    handleDetail(row) {
      const inventoryId = row.inventoryId;
      this.$router.push({ path: "/wms/inventory/detail", query: { inventoryId: inventoryId } });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.inventoryId != null) {
            updateInventory(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addInventory(this.form).then(response => {
              this.$modal.msgSuccess("入库成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 返回库位列表 */
    handleBack() {
      this.$router.push({ path: "/wms/location", query: { warehouseId: this.queryParams.warehouseId, areaId: this.queryParams.areaId } });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('wms/inventory/export', {
        ...this.queryParams
      }, `inventory_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>